#!/usr/bin/python2
# -*- coding: utf-8 -*-

# import threading
import time
import random

# from Queue import Queue
from eventlet import Queue,sleep

from topo import Topo
from dependency import DependencyGraph


class UpdateGenerator():
    def __init__(self,queue,queue1, ip1,ip2,port1,port2,topo,poisson_lambda= 1000):
        # super(UpdateGenerator, self).__init__()
        assert isinstance(queue,Queue)
        assert isinstance(topo,Topo)
        self.__queue_l = [queue, queue1]
        self.__ip1 = ip1
        self.__ip2 = ip2
        self.__port1 = port1
        self.__port2 = port2
        self.__topo = topo
        self.__lambda = poisson_lambda
        self.__select_queue = 0

    def switch_queue(self):
        self.__select_queue= (self.__select_queue+1)%2

    def poisson_interval(self):
        return random.expovariate(self.__lambda)

    def run(self):
        random.seed(hash(self.__ip1) * 7 + hash(self.__ip2) * 13)
        # poisson_interval = [random.expovariate(self.__lambda) for i in range(11)]

        sleep(self.poisson_interval())

        path1_2 = self.__topo.get_shortest_path(self.__port1,self.__port2)
        dep = DependencyGraph.construct(None, path1_2, self.__ip1, self.__ip2)
        dep.timestamp = time.time()
        self.__queue_l[self.__select_queue].put(dep)

        sleep(self.poisson_interval())


        # while count<1000:
        #     count+=1
        # for interval in poisson_interval[2:]:
        while True:
            interval = self.poisson_interval()
            new_path1_2 = self.__topo.random_change_path(path1_2)
            if new_path1_2 is None:
                print("new path is None")
                break
            print("path1_2",new_path1_2)
            dep = DependencyGraph.construct(path1_2, new_path1_2, self.__ip1, self.__ip2)
            dep.timestamp = time.time()
            self.__queue_l[self.__select_queue].put(dep)
            path1_2 = new_path1_2
            sleep(interval)
        # sleep(5)

    def set_lambda(self, la):
        self.__lambda = la
